package com.kevin.feign.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kevin.entity.BookPo;
import com.kevin.entity.ClothesPo;
import com.kevin.entity.FoodPo;
import com.kevin.feign.service.ISearchService;
import com.kevin.feign.service.remote.IBookService;
import com.kevin.feign.service.remote.IClothesService;
import com.kevin.feign.service.remote.IFoodService;
import com.kevin.feign.util.ResultObject;

@Service("searchService")
public class SearchServiceImpl implements ISearchService {

	@Autowired
	private IFoodService foodservice;
	@Autowired
	private IClothesService clothesService;
	@Autowired
	private IBookService bookservice;

	@Override
	public ResultObject listSearch(String keyword) {
		if(StringUtils.isBlank(keyword)){
			keyword = null;
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("keyword", keyword);
		List<FoodPo> foods = checkResult(FoodPo.class, foodservice.listFood(params));
		List<ClothesPo> clothes = checkResult(ClothesPo.class, clothesService.listClothes(params));
		List<BookPo> books = checkResult(BookPo.class, bookservice.listBook(params));
		List<Object> result = new ArrayList<Object>();
		if(foods!=null){
			result.addAll(foods);
		}
		if(clothes!=null){
			result.addAll(clothes);
		}
		if(books!=null){
			result.addAll(books);
		}
		return new ResultObject("100", "success", result);
	}

	@SuppressWarnings("unchecked")
	private <T> List<T> checkResult(Class<T> clazz, ResultObject result) {
		if (StringUtils.isBlank(result.getStatus()) || !"100".equals(result.getStatus())) {
			return null;
		}
		return (List<T>) result.getResult();
	}

}
